#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db import connection
import akshare as ak
import numpy as np
import datetime
import pandas as pd
import requests
from web.manager.log_manager import LogManager
from web.models import CommodityFutureDateData
from web.config.commodity_future_date_data_config import CommodityFutureDateDataConfig
from web.task.base_task import BaseTask

Logger = LogManager.get_logger(__name__)

"""
通过akshare下载期货历史数据
"""


class AkshareDownloadCommodityFutureDataTask(BaseTask):

    def download_commodity_future_date_data(self):
        """
        通过akshare下载日线级别期货历史数据
        """

        Logger.info("通过akshare下载日线级别期货历史数据")

        begin_date = CommodityFutureDateDataConfig.Commodity_Future_Date_Data_Basic_Data_Begin_Date
        end_date = CommodityFutureDateDataConfig.Commodity_Future_Date_Data_Basic_Data_End_Date
        Logger.info("下载期货交易数据的时间范围为：[%s]-[%s]", begin_date, end_date)
        begin_date = datetime.datetime.strptime(begin_date, "%Y%m%d")
        end_date = datetime.datetime.strptime(end_date, "%Y%m%d")

        with connection.cursor() as cursor:
            cursor.execute("select t.code, t.name from commodity_future_info t "
                           "where (instr(t.code, '-C/P')=0 and instr(t.code, '-CP')=0)")
            code_and_name_tuple = cursor.fetchall()

            for item in code_and_name_tuple:
                code = item[0]
                name = item[1]
                Logger.info('正在处理的期货数据：' + code + '  ' + name)

                # 下载数据
                symbol = code + '0'
                commodity_future_date_data_dataframe = ak.futures_zh_daily_sina(symbol=symbol)
                commodity_future_date_data_dataframe = commodity_future_date_data_dataframe.rename(
                    columns={
                        "日期": "date",
                        "开盘价": "open",
                        "最高价": "high",
                        "最低价": "low",
                        "收盘价": "close",
                        "成交量": "volume",
                        "持仓量": "hold",
                        "动态结算价": "settle",
                    }
                )

                # 保存数据
                for index, row in commodity_future_date_data_dataframe.iterrows():
                    commodity_future_date_data = CommodityFutureDateData()
                    commodity_future_date_data.code = code
                    commodity_future_date_data.name = name
                    commodity_future_date_data.transaction_date = row.values[0]

                    # 判断是否在时间范围内
                    transaction_date = datetime.datetime.strptime(commodity_future_date_data.transaction_date,
                                                                  "%Y-%m-%d")
                    if transaction_date < begin_date or transaction_date > end_date:
                        continue

                    commodity_future_date_data.open_price = row.values[1]
                    commodity_future_date_data.highest_price = row.values[2]
                    commodity_future_date_data.lowest_price = row.values[3]
                    commodity_future_date_data.close_price = row.values[4]
                    commodity_future_date_data.turnover = row.values[5]
                    commodity_future_date_data.open_interest = row.values[6]
                    commodity_future_date_data.save()
